package com.didi.gulimall.member.interceptor;

import com.didi.gulimall.common.constant.AuthServerConstant;
import com.didi.gulimall.common.constant.BizCodeEnume;
import com.didi.gulimall.common.constant.SystemConstant;
import com.didi.gulimall.common.to.MemberResponseVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author 10626
 * @Create 2021/5/30 0:15
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    @Value("${gulimall.login}")
    private String loginHtml;

    public static ThreadLocal<MemberResponseVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean orderStatus = antPathMatcher.match("oauth/weibo/login", uri);
        boolean payedNotify = antPathMatcher.match("/payed/notify", uri);
        if (orderStatus||payedNotify){
            return true;
        }
        HttpSession session = request.getSession();
        MemberResponseVo memberRes = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (memberRes !=null){
            loginUser.set(memberRes);
            return true;
        }else {
            response.sendRedirect(loginHtml);
            request.getSession().setAttribute(SystemConstant.ERRORS, BizCodeEnume.PLEASE_SIGN_IN.getMsg());
            return false;
        }
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        loginUser.remove();
    }
}
